package com.wu.server.websocket;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Wugs
 * @version 1.0
 * @date 2021/3/2 22:05
 */
@Component
@ServerEndpoint("/meta")
public class MetaWebSocket {
    static Session session;
    //定义Websocket容器，储存session
    private static CopyOnWriteArraySet<MetaWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
    @OnOpen
    public void opOpen(Session session) {
        MetaWebSocket.session = session;
        System.out.println("状态监听连接成功");
    }
    @OnClose
    public void onClose(){
        System.out.println("连接关闭");
        webSocketSet.remove(this);
    }
    //发送消息
    public static void sendMessage(String obj){
        //遍历储存的Websocket
        try {
            MetaWebSocket.session.getBasicRemote().sendText(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
